package tool

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
)

// 进行成查看
type Progress struct {
	Id    string
	Show  string
	Finsh int
}

var (
	mux sync.Mutex
	m   map[string]Progress = make(map[string]Progress)
)

func CurrentDir(joinPath ...string) (string, error) {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		return "", err
	}
	p := strings.Replace(dir, "\\", "/", -1)
	whole := filepath.Join(joinPath...)
	whole = filepath.Join(p, whole)
	return whole, nil
}

func ResolveURL(u *url.URL, p string) string {
	if strings.HasPrefix(p, "https://") || strings.HasPrefix(p, "http://") {
		return p
	}
	var baseURL string
	if strings.Index(p, "/") == 0 {
		baseURL = u.Scheme + "://" + u.Host
	} else {
		tU := u.String()
		baseURL = tU[0:strings.LastIndex(tU, "/")]
	}
	return baseURL + path.Join("/", p)
}

func DrawProgressBar(prefix string, proportion float32, width int, suffix ...string) {
	pos := int(proportion * float32(width))
	s := fmt.Sprintf("[%s] %s%*s %6.2f%% %s",
		prefix, strings.Repeat("■", pos), width-pos, "", proportion*100, strings.Join(suffix, ""))
	fmt.Print("\r" + s)
}

func IsValidURL(fileUrl string) bool {
	_, err := url.ParseRequestURI(fileUrl)
	if err != nil {
		return false
	}

	u, err := url.Parse(fileUrl)
	if err != nil {
		return false
	}

	return u.Scheme == "http" || u.Scheme == "https"
}

func GetMd5(str string) string {
	// 创建一个新的md5哈希对象
	hasher := md5.New()
	// 将字符串转换为字节数组并写入哈希对象
	hasher.Write([]byte(str))
	// 计算哈希值的字节数组
	hashBytes := hasher.Sum(nil)
	// 将字节数组转换为十六进制字符串
	return hex.EncodeToString(hashBytes)
}

// 查看进度
func GetProgress(id string) *Progress {
	mux.Lock()
	defer mux.Unlock()
	val, ok := m[id]
	if ok {
		return &val
	}
	return nil
}

// 设置进度
func SetProgress(id string, show string, finsh int) {
	mux.Lock()
	p := Progress{
		Id:    id,
		Show:  show,
		Finsh: finsh,
	}
	m[id] = p
	mux.Unlock()
}
